package com.example.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/5 23:48
 * @since JDK 1.8
 */
@Configuration
@Slf4j
@EnableTransactionManagement
public class MybatilsPlusConfig implements MetaObjectHandler {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 向MyBatis-Plus的过滤器链中添加分页拦截器，需要设置数据库类型（主要用于分页方言）
        interceptor.addInnerInterceptor(paginationInterceptor());
        // 添加乐观锁拦截器
        //interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }


    public PaginationInnerInterceptor paginationInterceptor() {
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        // 设置数据库方言，默认为MySQL，可以根据实际情况进行配置
        paginationInterceptor.setDbType(DbType.MYSQL);
        // 设置是否进行 count 查询，默认为 true，可以根据需求进行配置
        paginationInterceptor.setOverflow(true);
        // 设置单页最大限制数量，默认为 -1（无限制），可以根据实际需求进行配置
        paginationInterceptor.setMaxLimit(1000L);
        return paginationInterceptor;
    }

    //配置开发环境使用可以监测sql执行效率的插件
    @Bean
    public PerformanceMonitorInterceptor performanceInterceptor() {
        return new PerformanceMonitorInterceptor();
    }


    /**
     * 乐观锁机制
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    /**
     * 新增时的填充策略
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill....."+metaObject.toString());
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("version",0,metaObject);
        this.setFieldValByName("deleteStatus",0,metaObject);
    }

    /**
     * 更新填充处理
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("tart update fill...."+metaObject.toString());
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

}
